package com.OneCommerceProject.controllers;

import com.OneCommerceProject.entities.Fournisseur;
import com.OneCommerceProject.controllers.util.JsfUtil;
import com.OneCommerceProject.controllers.util.PaginationHelper;
import com.OneCommerceProject.beans.FournisseurFacade;
import com.OneCommerceProject.beans.ItemFacade;
import com.OneCommerceProject.beans.ItemFourFacade;
import com.OneCommerceProject.entities.Item;
import com.OneCommerceProject.entities.ItemFour;
import com.OneCommerceProject.entities.ItemFourPK;

import java.io.Serializable;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.List;
import java.util.ResourceBundle;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.component.UIComponent;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;
import javax.faces.model.DataModel;
import javax.faces.model.ListDataModel;
import javax.faces.model.SelectItem;
import org.primefaces.event.TabChangeEvent;

@ManagedBean(name = "fournisseurController")
@SessionScoped
public class FournisseurController implements Serializable {

    private Fournisseur current;
    private Fournisseur fournisseur;
    private ItemFour itemFour;    
    private Item Item = null;
    private BigDecimal idItem;
    private DataModel items = null;
    @EJB
    private com.OneCommerceProject.beans.FournisseurFacade ejbFacade;
    private PaginationHelper pagination;
    private int selectedItemIndex;
    @EJB
    private ItemFacade itemFacade;    
    @EJB
    private ItemFourFacade itemFourFacade;
    private boolean chooseFour = false;    
    private boolean leader = true;

    public boolean isChooseFour() {
        return chooseFour;
    }

    public boolean isLeader() {
        return leader;
    }
    
    public Fournisseur getFournisseur() {
        return fournisseur;
    }

    public void setFournisseur(Fournisseur fournisseur) {
        this.fournisseur = fournisseur;
    }
    
    public void onTabChange(TabChangeEvent event) {        
        chooseFour = !chooseFour;        
    }    

    public void setLeader() {
        try {
            if (idItem == null) {
                ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
                String itemId = externalContext.getRequestParameterMap().get("item");
                idItem = new BigDecimal(itemId);
            }            
            itemFour = getItemFourFacade().findItemFour(idItem, fournisseur.getIdfour());
            ItemFour itemFourLeader = getItemFourFacade().findItemLeader(idItem);
            itemFourLeader.setLeader(false);
            getItemFourFacade().edit(itemFourLeader);            
            itemFour.setLeader(true);
            getItemFourFacade().edit(itemFour);
            JsfUtil.addSuccessMessage(fournisseur.getNomfour() + " is the leader of this item");        
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));            
        }
    }    
    
    public FournisseurController() {
    }    
   
    
    public Fournisseur getSelected() {
        if (current == null) {
            current = new Fournisseur();
            selectedItemIndex = -1;
        }
        return current;
    }

    private FournisseurFacade getFacade() {
        return ejbFacade;
    }
    
    private ItemFourFacade getItemFourFacade() {
        return itemFourFacade;
    }
    
    public PaginationHelper getPagination() {
        if (pagination == null) {
            pagination = new PaginationHelper(10) {

                @Override
                public int getItemsCount() {
                    return getFacade().count();
                }

                @Override
                public DataModel createPageDataModel() {
                    return new ListDataModel(getFacade().findRange(new int[]{getPageFirstItem(), getPageFirstItem() + getPageSize()}));
                }
            };
        }
        return pagination;
    }

    public String prepareList() {
        recreateModel();
        return "List";
    }

    public String prepareView() {
        current = (Fournisseur) getItems().getRowData();
        selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
        return "View";
    }

    public String prepareCreate() {
        current = new Fournisseur();
        selectedItemIndex = -1;
        return "Create";
    }
    
    public void setItemFour(){
        itemFour = new ItemFour();
        itemFour.setFournisseur(current);
        ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
        String itemId = externalContext.getRequestParameterMap().get("item_id");
        Item item = itemFacade.findByIdItem(new BigDecimal(itemId));
        itemFour.setItem(item);
        itemFour.setLeader(false);
        getItemFourFacade().create(itemFour);        
    }
    
    public void createItemFour() {
        getItem();
        itemFour = new ItemFour();
        itemFour.setFournisseur(current);
        itemFour.setItem(Item);
        itemFour.setLeader(false);
        ItemFourPK itemFourPK = new ItemFourPK(Item.getIditem(), current.getIdfour());
        itemFour.setItemFourPK(itemFourPK);
        System.out.println("itemFour: " + itemFour);
        getItemFourFacade().create(itemFour);
    }

    private void getItem() {
        if (Item == null) {
            ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
            String itemId = externalContext.getRequestParameterMap().get("item");
            Item newItem = itemFacade.findByIdItem(new BigDecimal(itemId));
            Item = newItem;
        }
    }
    
    public String create() {                
        try {          
            current.setIdfour(null);
            getFacade().create(current);            
            createItemFour();
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("FournisseurCreated"));
            current = new Fournisseur();
            selectedItemIndex = -1;
            return null;
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
            return null;
        }
    }

    public String prepareEdit() {
        current = (Fournisseur) getItems().getRowData();
        selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
        return "Edit";
    }

    public String update() {
        try {
            getFacade().edit(current);
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("FournisseurUpdated"));
            return "View";
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
            return null;
        }
    }

    public String destroy() {
        current = (Fournisseur) getItems().getRowData();
        selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
        performDestroy();
        recreatePagination();
        recreateModel();
        return "List";
    }

    public String destroyAndView() {
        performDestroy();
        recreateModel();
        updateCurrentItem();
        if (selectedItemIndex >= 0) {
            return "View";
        } else {
            // all items were removed - go back to list
            recreateModel();
            return "List";
        }
    }

    private void performDestroy() {
        try {
            getFacade().remove(current);
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("FournisseurDeleted"));
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
        }
    }

    private void updateCurrentItem() {
        int count = getFacade().count();
        if (selectedItemIndex >= count) {
            // selected index cannot be bigger than number of items:
            selectedItemIndex = count - 1;
            // go to previous page if last page disappeared:
            if (pagination.getPageFirstItem() >= count) {
                pagination.previousPage();
            }
        }
        if (selectedItemIndex >= 0) {
            current = getFacade().findRange(new int[]{selectedItemIndex, selectedItemIndex + 1}).get(0);
        }
    }

    public DataModel getItems() {
        if (items == null) {
            items = getPagination().createPageDataModel();
        }
        return items;
    }

    private void recreateModel() {
        items = null;
    }

    private void recreatePagination() {
        pagination = null;
    }

    public String next() {
        getPagination().nextPage();
        recreateModel();
        return "List";
    }

    public String previous() {
        getPagination().previousPage();
        recreateModel();
        return "List";
    }

    public SelectItem[] getItemsAvailableSelectMany() {
        return JsfUtil.getSelectItems(ejbFacade.findAll(), false);
    }

    public SelectItem[] getItemsAvailableSelectOne() {
        return JsfUtil.getSelectItems(ejbFacade.findAll(), true);
    }

    @FacesConverter(forClass = Fournisseur.class)
    public static class FournisseurControllerConverter implements Converter {

        public Object getAsObject(FacesContext facesContext, UIComponent component, String value) {
            if (value == null || value.length() == 0) {
                return null;
            }
            FournisseurController controller = (FournisseurController) facesContext.getApplication().getELResolver().
                    getValue(facesContext.getELContext(), null, "fournisseurController");
            return controller.ejbFacade.find(getKey(value));
        }

        java.math.BigDecimal getKey(String value) {
            java.math.BigDecimal key;
            key = new java.math.BigDecimal(value);
            return key;
        }

        String getStringKey(java.math.BigDecimal value) {
            StringBuffer sb = new StringBuffer();
            sb.append(value);
            return sb.toString();
        }

        public String getAsString(FacesContext facesContext, UIComponent component, Object object) {
            if (object == null) {
                return null;
            }
            if (object instanceof Fournisseur) {
                Fournisseur o = (Fournisseur) object;
                return getStringKey(o.getIdfour());
            } else {
                throw new IllegalArgumentException("object " + object + " is of type " + object.getClass().getName() + "; expected type: " + FournisseurController.class.getName());
            }
        }
    }
}
